package com.bdqn.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.demo.dao.RoleDao;
import com.bdqn.demo.dao.UserDao;
import com.bdqn.demo.pojo.Role;
import com.bdqn.demo.pojo.User;
import com.bdqn.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2024-01-16 19:08:23
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService, UserDetailsService {

    @Autowired
    private RoleDao roleDao;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername, username);
        lqw.eq(User::getEnabled, 1);
        User user = getOne(lqw);
        if (user == null) {
            throw new UsernameNotFoundException("账号或密码错误!");
        }
        Role role = roleDao.selectByUid(user.getId());
        user.setAuthorities(AuthorityUtils.createAuthorityList(role.getName()));

        return user;
    }


    @Override
    public IPage<User> userByUsername(String username, Integer pageNo, Integer pageSize) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.like(User::getUsername, username);
        lqw.eq(User::getEnabled, 1);
        IPage<User> page = new Page<>();
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        return page(page, lqw);
    }

    @Override
    public boolean deleteById(Integer id) {
        return update().set("enabled", 0).eq("id", id).update();

    }
}

